def read_srt(srt_file):
    """读取SRT文件，返回时间码和字幕文本的列表"""
    with open(srt_file, 'r', encoding='utf-8') as f:
        content = f.read().strip()
    
    blocks = content.split('\n\n')
    subtitles = []
    
    for block in blocks:
        lines = block.split('\n')
        if len(lines) >= 3:  # 确保块至少包含序号、时间码和文本
            number = lines[0]
            timestamp = lines[1]
            text = '\n'.join(lines[2:])
            subtitles.append((number, timestamp, text))
    
    return subtitles

def read_translation(translation_file):
    """读取翻译文本文件，返回翻译文本列表"""
    with open(translation_file, 'r', encoding='utf-8') as f:
        translations = [line.strip() for line in f if line.strip()]
    return translations

def create_new_srt(subtitles, translations, output_file):
    """创建新的SRT文件，使用翻译文本替换原始文本"""
    if len(subtitles) != len(translations):
        raise ValueError("字幕数量与翻译数量不匹配！")
    
    with open(output_file, 'w', encoding='utf-8') as f:
        for (number, timestamp, _), translation in zip(subtitles, translations):
            f.write(f"{number}\n")
            f.write(f"{timestamp}\n")
            f.write(f"{translation}\n\n")

def main():
    # 文件路径
    srt_file = input("请输入SRT文件路径: ")
    translation_file = input("请输入翻译文本文件路径: ")
    output_file = "output.srt"
    
    try:
        # 读取原始SRT文件
        subtitles = read_srt(srt_file)
        
        # 读取翻译文本
        translations = read_translation(translation_file)
        
        # 创建新的SRT文件
        create_new_srt(subtitles, translations, output_file)
        
        print(f"转换完成！新文件已保存为: {output_file}")
        
    except Exception as e:
        print(f"发生错误: {str(e)}")

if __name__ == "__main__":
    main() 